from typing import Dict, List

from elasticsearch import Elasticsearch
import sys
sys.path.append("../workflow4threeman")
from workflow.Configuration import DataBaseConfig
from workflow.TextPayLoad import TextPayLoad
from workflow.NetPayLoad import NetPayLoad


class ElasticSearchConfig:
    """
        es数据库的各项设置
    """
    
    HOST = DataBaseConfig.ElasticSearch.HOST
    PORT = DataBaseConfig.ElasticSearch.PORT

class ElasticSearchDataExtractor:
    
    def __init__(self, es_config: ElasticSearchConfig) -> None:
        self.config = es_config
        #TODO 找出下段无法运行的方法
        # self.es_database = Elasticsearch(
        #     [
        #         {'host': self.config.HOST, 
        #          'port': self.config.PORT,
        #          }
        #     ]
        # )
        self.es_database = Elasticsearch(hosts="219.224.134.224:9211",timeout=100)
        
    def get_text(self, range: List=None,sensitive_word:str=None, ) -> TextPayLoad:
        """
        根据给定的时间范围，指定关键词，搜索相关文本，并进行LDA主题建模
        """
        TPL = TextPayLoad()
        raw_texts_list = list()

        # q_body = {
        #         "query":{
        #             "match_all":{}
        #     }
        # }
        q_body = {"query":{"bool":{"must":[{"match_all":{}}],"must_not":[],"should":[]}},"from":0,"size":2000,"sort":[],"aggs":{}}
        dict_list = self.es_database.search(index='flow_text_2019-06-30',body=q_body)['hits']['hits']
        TPL.raw_text = [d['_source']['text'] for d in dict_list]
        return TPL

    def get_flowtext(self, time_range: List=None,sensitive_word:str=None, ) -> NetPayLoad:
        """
        给定时间范围和关键词（TODO）搜索微博文本流
        """
        NP = NetPayLoad()

        #初始条一般由关键词检索出来 for demo root_mid = 4392911510359513
        #1-step find the original weibo_text
        #2-step find all relevant weibo_text
        q_body = {
            "query":{
                "bool":{
                    "must":[
                        {
                            "term":{
                                "root_mid":4392927936052662
                            }
                        },
                        {
                            "term":{
                                "message_type":5
                            }
                        }
                    ]
                }
            }
        }
        #3-step return relevant weibo_text_flow
        NP.raw_flowtext = self.es_database.search(index='flow_text_2019-07-13',body=q_body)['hits']['hits']

        return NP

    def get_uid(self,uname:str,) -> int:
        """
        在weibo_user_big大表中搜索用户id:u_id
        uname:user name 用户名
        """
        q_body = {
            "query":{
                "match":{
                    "name":uname
                }
            }
        }
        
        return self.es_database.search(index='weibo_user_big',body=q_body)['hits']['hits'][0]['_source']['u_id']
